package com.molange.behavior.interceptor;

import com.molange.behavior.utils.BehaviorThreadLocalUtil;
import com.molange.model.user.pojos.AppUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wangshiqi
 * @version 1.0
 * @date 2023/1/14 14:43
 */
public class BehaviorTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //得到header中的信息
        String userId = request.getHeader("userId");
        System.out.println("behavior微服务拦截器获取的用户id"+userId);
        if(userId != null){
            //把用户id存入threadloacl中
            AppUser appUser=new AppUser();
            appUser.setId(Integer.valueOf(userId));
            BehaviorThreadLocalUtil.setUser(appUser);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BehaviorThreadLocalUtil.clear();
    }
}
